package com.example.zheng.els2.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zheng.els2.R;
import com.example.zheng.els2.service.MusicService;
import com.example.zheng.els2.service.NotificationService;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class GameActivity extends AppCompatActivity implements View.OnClickListener{
    public FrameLayout gameFrame;
    public View gameView;

    //下一块布局
    FrameLayout nextBlocakFrame;
    //下一块视图
    View nextBlockView;


    //游戏区域的宽度
    public int widthX;
    //游戏区域的高度
    public int heightY;

    //声明一个地图
    boolean[][] maps;
    //声明一个方块
    Point[] boxs;

    //声明下一块方块
    Point[] nextBox;
    //下一块方块的大小
    int nextBoxsSize=30;
    //声明下一个方块的类型
    int nextType;

    //地图辅助线
    Paint paintLine;

    //方块画笔
    Paint boxLine;

    //地图画笔
    Paint mapLine;

    //游戏状态画笔
    Paint gameStateLine;

    //方块的大小
    int boxsSize;
    //方块的类型
    int type;

    //方块下落的线程
    Thread thread;

    //是否暂停
    boolean ispasue=false;

    //是否出界
    boolean isBorder=false;

    //是否结束
    boolean isOver=false;

    //是否表扬过
    boolean isPraise=false;
    //异步刷新
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //刷新gameView
            gameView.invalidate();
            nextBlockView.invalidate();
            //设置文本内容
            currentScore.setText(score+"");
            //不断刷新在页面
            heightestScore.setText(mostScore+"");



            //当前分数小于30等级为1,大于30小于60等级为2,大于60小于180等级为3,大于180等级为4
            if(score>30&&score<=60){
                rankScore=2;
                speed=600;
                game.setBackgroundColor(0xFFEFE99A);
            }else if(score>60&&score<=180){
                rankScore=3;
                speed=400;
                game.setBackgroundColor(0xFFAAE2ED);


            }else if(score>180){
                if(!isPraise){
                    Toast.makeText(GameActivity.this,"How good are you!",Toast.LENGTH_SHORT).show();
                    isPraise=true;
                }
                rankScore=4;
                speed=250;
                game.setBackgroundColor(0xFF51360C);

            }else{
                rankScore=1;
                speed=800;
                game.setBackgroundColor(0xFFEACCCC);
            }
            //刷新等级
            rank.setText(rankScore+"");

            //判断游戏是否结束
            if(isOver){
                //存储最高分
                editor.putInt(playName,mostScore);
                //调用apply()方法将添加的数据提交，完成数据存储的操作
                editor.apply();
                alertDialog.setMessage("总共积"+score+"分");
                //如果游戏结束了，就弹出游戏结束的对话框
                alertDialog.setPositiveButton("再来一次", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //中断线程
                        thread.interrupt();
                        //游戏一结束就将子线程赋空，以便下次开始游戏时另开线程
                        thread=null;
                        isOver=false;
                        startGame();

                    }
                });
                alertDialog.setNegativeButton("退出游戏", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //中断线程
                        thread.interrupt();
                        //游戏一结束就将子线程赋空，以便下次开始游戏时另开线程
                        thread=null;
                        //结束掉本活动之前先结束掉对话框
                        dialog.dismiss();

                        //结束掉本活动
                        finish();
                    }
                });
                dialog=alertDialog.create();
                if(!isFinishing()) {
                    dialog.show();

                }



            }




        }
    };

    //定义一个总积分
    int score=0;
    //定义一个最高分
    int mostScore=0;
    //定义一个等级
    int rankScore=1;

    //定义一个背景颜色
    //String bgcolor=


    //方块下落的速度
    int speed=800;

    //定义一个对话框
    AlertDialog.Builder alertDialog;
    AlertDialog dialog;

    //定义一个SharedPerferences对象，用于读取数据
    SharedPreferences mostShared;

    //定义一个SharedPerfernces对象，用于存储数据
    SharedPreferences.Editor editor;
   //得到该活动的LinearLayout布局
    LinearLayout game;



    //定义所有控件
    private Button restart;
    private ImageView rotate;
    private ImageView down;
    private ImageView rapid;
    private ImageView left;
    private ImageView right;
    private Button pasue;

    //定义所有的文本
    private TextView heightestScore;
    private TextView currentScore;
    private TextView player;
    private TextView rank;

    //定义一个通知的意图
    Intent notifyIntent;

    //定义一个音乐意图
    Intent musicIntent;

    //初始化一个消行铃声播放器
    MediaPlayer mediaPlayer1;

    //定义一个音效池
    SoundPool soundPool;
    Map<Integer,Integer> soundPoolMap;

    //定义一个玩家
    String playName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //去掉手机上的状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.game);

        //初始化数据
        initData();

        //初始化视图
        initView();

        //声明一个二维数组boolean型的地图
        maps=new boolean[10][20];

        //给当前方块赋值
        newBox();

        boxsSize=widthX/maps.length;

        //实例化SharedPerferences对象
        mostShared=getSharedPreferences("data",MODE_PRIVATE);

        //实例化SharedPerfernces.Editor 对象
        editor=mostShared.edit();


        //游戏一启动及开始游戏
        startGame();





        //初始化对话框
        alertDialog=new AlertDialog.Builder(GameActivity.this);
        alertDialog.setTitle("游戏结束");
        alertDialog.setCancelable(false);






        //获取按钮
        restart=(Button)findViewById(R.id.restart);
        pasue=(Button)findViewById(R.id.pasue);
        rotate=(ImageView)findViewById(R.id.rotate);
        down=(ImageView)findViewById(R.id.down);
        left=(ImageView)findViewById(R.id.left);
        right=(ImageView)findViewById(R.id.right);
        rapid=(ImageView)findViewById(R.id.rapid);

        //获取到文本
        heightestScore=(TextView)findViewById(R.id.hightestScore);
        currentScore=(TextView)findViewById(R.id.currentScore);
        player=(TextView)findViewById(R.id.player);
        rank=(TextView)findViewById(R.id.rank);


        //监听事件
        restart.setOnClickListener(this);
        pasue.setOnClickListener(this);
        rotate.setOnClickListener(this);
        down.setOnClickListener(this);
        left.setOnClickListener(this);
        right.setOnClickListener(this);
        rapid.setOnClickListener(this);

        if(playName==null){
            player.setText("游客");
        }else{
            player.setText(playName);
        }






    }
    public void initView(){

        game=(LinearLayout)findViewById(R.id.game);

        //得到下一块方块的容器
        nextBlocakFrame=(FrameLayout)findViewById(R.id.nextBlock);
        //实例化下一块区域
        nextBlockView=new View((this)){
            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);

                if(nextBox!=null){
                    //绘制下一块方块
                    for(int i=0;i<nextBox.length;i++) {

                        canvas.drawRect((nextBox[i].x-2)*nextBoxsSize,(nextBox[i].y+2)*nextBoxsSize,(nextBox[i].x-2)*nextBoxsSize+nextBoxsSize,(nextBox[i].y+2)*nextBoxsSize+nextBoxsSize,boxLine);
                    }
                }


            }
        };
        //设置下一块区域的大小
        nextBlockView.setLayoutParams(new TableRow.LayoutParams(-2,200));

        //设置背景颜色
        nextBlockView.setBackgroundColor(0xFF000000);

        //添加到下一块容器中
        nextBlocakFrame.addView(nextBlockView);




        //得到游戏容器
        gameFrame=(FrameLayout)findViewById(R.id.gameFrame);
        //实例化游戏区域
        gameView=new View(this){

            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);

                //绘制地图
                for(int x=0;x<maps.length;x++){
                    for(int y=0;y<maps[x].length;y++){
                        //遍历时如果已经有方块，将方块变成蓝色
                        if(maps[x][y]==true)
                            canvas.drawRect(x*boxsSize,y*boxsSize,x*boxsSize+boxsSize,y*boxsSize+boxsSize,mapLine);
                    }
                }

                //绘制方块
                for(int i=0;i<boxs.length;i++){
                    canvas.drawRect(boxs[i].x*boxsSize,boxs[i].y*boxsSize,boxs[i].x*boxsSize+boxsSize,boxs[i].y*boxsSize+boxsSize,boxLine);
                }

                //绘制地图辅助线
                for(int x=0;x<maps.length;x++){
                    canvas.drawLine(x*boxsSize,0,x*boxsSize,gameView.getHeight(),paintLine);
                }
                for(int y=0;y<maps[0].length;y++){
                    canvas.drawLine(0,y*boxsSize,gameView.getHeight(),y*boxsSize,paintLine);
                }

                //绘制游戏状态
                if(ispasue){
                    canvas.drawText("暂停",widthX/2-gameStateLine.getTextSize(),heightY/2,gameStateLine);

                }
            }
        };

        //设置游戏区域的大小
        gameView.setLayoutParams(new TableRow.LayoutParams(widthX,heightY));

        //设置背景颜色
        gameView.setBackgroundColor(0xFF000000);

        //添加到游戏容器中
        gameFrame.addView(gameView);




    }

    //初始化数据
    public void initData(){
        //初始化地图辅助线
        paintLine=new Paint();
        paintLine.setColor(Color.WHITE);
        paintLine.setAntiAlias(true);


        //初始化方块画笔
        boxLine=new Paint();
       // boxLine.setColor(Color.GREEN);
        boxLine.setAntiAlias(true);



        //初始化地图画笔
        mapLine=new Paint();
        mapLine.setColor(Color.BLUE);
        mapLine.setAntiAlias(true);


        //初始化游戏状态画笔
        gameStateLine=new Paint();
        gameStateLine.setColor(Color.GRAY);
        gameStateLine.setAntiAlias(true);
        gameStateLine.setTextSize(100f);


        int  ScreeWidth=getScreenWidth(this);
        widthX=2*ScreeWidth/3;
        heightY=2*widthX;


        //得到当前玩家
        playName=getIntent().getStringExtra("player");


        //初始化一个音效池，第一个参数是可以同时播放几个音效，第二个参数是音频类型，第三个是音频质量
        soundPool=new SoundPool(8, AudioManager.STREAM_MUSIC,100);
        soundPoolMap=new HashMap<>();
        //第一个参数是音效,第二个是加载音效
        soundPoolMap.put(1, soundPool.load(this, R.raw.delete, 1));
        soundPoolMap.put(2, soundPool.load(this, R.raw.gameover, 1));

        musicIntent=new Intent(this,MusicService.class);


    }
    public void playsound(int i){
        AudioManager mgr = (AudioManager) this
                .getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;
        //音效池播放
        soundPool.play(soundPoolMap.get(i), volume, volume, 1, 0, 1f);

    }


    //获取屏幕的宽度

    public int getScreenWidth(Context context){
        WindowManager manager=(WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        DisplayMetrics display =new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(display);
        return display.widthPixels;
    }


    //给按钮绑定监听事件，做出相应的操作
    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.restart:
                if(notifyIntent!=null){
                    stopService(notifyIntent);
                }
                startGame();

                break;

            case R.id.pasue:
                if(!ispasue) {
                    ispasue = true;
                }else{
                    ispasue=false;
                }
                if(notifyIntent!=null){
                    stopService(notifyIntent);
                }

                break;

            case R.id.rotate:
                rotate();
                break;

            case R.id.down:
                if(ispasue)
                    break;
                move(0,1);

                break;

            case R.id.left:
                if(ispasue)
                    break;
                move(-1,0);

                break;

            case R.id.right:
                if(ispasue)

                    break;
                move(1,0);
                break;

            case R.id.rapid:
                if(ispasue||isOver)
                    break;
                while(true) {
                    if (!moveBottom()) {
                        break;
                    }
                }



        }
        //刷新游戏视图
        gameView.invalidate();


    }


    //方块旋转
    public boolean rotate() {
        if(type==0||ispasue)
        {
            return false;
        }
        for(int i=0;i<boxs.length;i++){
            int x=-boxs[i].y+boxs[0].y+boxs[0].x;
            int y=boxs[i].x-boxs[0].x+boxs[0].y;
            isBorder=isBorder(x,y);
            if(isBorder){
                return false;
            }

        }
        for(int i=0;i<boxs.length;i++) {
            int x = -boxs[i].y + boxs[0].y + boxs[0].x;
            int y = boxs[i].x - boxs[0].x + boxs[0].y;
            boxs[i].x = x;
            boxs[i].y = y;
        }
        return true;

    }


    //开始游戏，并让方块每隔0.8秒自动下落
    public void startGame() {
        //只要一开始游戏就开启背景音乐服务
        startService(musicIntent);
        //每次点击开始游戏按钮，游戏就会重新开始，游戏视图里面的方块就没有了，重新生成方块
        for(int x=0;x<maps.length;x++){
            for(int y=0;y<maps[x].length;y++){
                maps[x][y]=false;
            }
        }

        //重新开始游戏时会暂停取消
        ispasue=false;

        //重新开始游戏时，会将积分归零
        score=0;

        //得到本地存储的最高分
        mostScore=mostShared.getInt(playName,0);

        //重新生成新的方块
        randomBlock();
        if(thread==null){
            thread=new Thread(){

                @Override
                public void run() {
//                    super.run();
                    while (!isOver){
                        //move(0,1);
                        try {
                            sleep(speed);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        //游戏开始时就要判断游戏是否结束
                        gameOver();


                        //游戏开始就做消行处理
                        deleteline();

                        //如果最高分数小于当前分数，就将当前分数赋给最高分数
                        if(mostScore<score){
                            mostScore=score;

                        }

                        if(ispasue){

                            continue;
                        }
                        moveBottom();

                        //通知主线程刷新gameView
                        handler.sendEmptyMessage(0);
                    }
                    playsound(2);
                    stopService(musicIntent);
                }
            };
            thread.start();




        }

    }


    //当游戏区从底端到顶端都为true，说明方块已达顶端，这为游戏结束
    public void gameOver(){
        for(int i=0;i<boxs.length;i++){
            if(maps[boxs[i].x][boxs[i].y]){
                isOver=true;

            }
        }
    }
    //消行处理
    public void deleteline() {
        int countLines=0;
        for (int y = 0; y < maps[0].length; y++) {

            if(cleanLine(y)){
                playsound(1);
                delete(y);

                //消掉一行时，就开始计数
                countLines++;
            }

        }

        if(countLines==0){
            return;
        }
        score+=2*countLines-1;

    }

    //执行消行
    public void delete(int z){
        for(int y=z;y>0;y--){
            for(int x=0;x<maps.length;x++) {
                maps[x][y] = maps[x][y - 1];

            }

        }
        //只要一消掉某行就响一次





    }

    //判断是否可以消行
    public boolean cleanLine(int y){
        for(int x=0;x<maps.length;x++) {
            if (!maps[x][y]) {
                return false;
            }

        }
        return true;
    }

    //方块向左向右向下移动时，其横纵坐标加上其偏移量
    private boolean move(int x, int y) {
        for(int i=0;i<boxs.length;i++) {
            //当方块执行了移动而导致出界的话，返回false
            if (isBorder(boxs[i].x+x, boxs[i].y+y)) {
                return false;
            }
        }


        for(int i=0;i<boxs.length;i++){
            boxs[i].x+=x;
            boxs[i].y+=y;

        }
        return true;
    }

    //方块直接移到底端
    public boolean moveBottom(){

        //移动成功时则结束方法
        if(move(0,1)){
            return true;
        }

        //移动失败时，就开始堆积
        for(int i=0;i<boxs.length;i++){
            maps[boxs[i].x][boxs[i].y]=true;
        }
        randomBlock();
        return false;
    }


    //边界值判断，当方块被判断下一步会出界就返回true
    private boolean isBorder(int x,int y) {
        if(x<0||y<0||x>=maps.length||y>=maps[0].length||maps[x][y]){
            isBorder=true;
            return true;
        }
        return false;


    }


    //随机生成一个方块和下一个方块
    public  void randomBlock(){
        //一个方块为空时，则随机生成一个
        if(nextBox==null){
            newBox();
        }
        //把下一个方块赋给当前方块
        boxs=nextBox;
        //当前方块的类型=下个方块的类型
        type=nextType;
        //再随机生成下一个方块
        newBox();

    }

    //随机生成7种方块
    public void newBox(){

        Random random=new Random();
        nextType=random.nextInt(7);

        switch (nextType){
            //田字型
            case 0:
                nextBox=new Point[]{new Point(3,0),new Point(4,0),new Point(3,1),new Point(4,1)};
                boxLine.setColor(Color.YELLOW);
                break;
            //直条型
            case 1:
                nextBox=new Point[]{new Point(3,0),new Point(4,0),new Point(5,0),new Point(6,0)};
                boxLine.setColor(Color.RED);
                break;

            //Z字型
            case 2:
                nextBox=new Point[]{new Point(3,0),new Point(4,0),new Point(4,1),new Point(5,1)};
                boxLine.setColor(Color.GREEN);
                break;

            //床铺型
            case 3:
                nextBox=new Point[]{new Point(3,0),new Point(3,1),new Point(4,1),new Point(5,1)};
                boxLine.setColor(Color.YELLOW);
                break;

            //凸型
            case 4:
                nextBox=new Point[]{new Point(3,0),new Point(4,0),new Point(5,0),new Point(4,1)};
                boxLine.setColor(Color.RED);
                break;

            //闪电型
            case 5:
                nextBox=new Point[]{new Point(3,0),new Point(3,1),new Point(4,1),new Point(4,2)};
                boxLine.setColor(Color.RED);
                break;

            //锄头型
            case 6:
                nextBox=new Point[]{new Point(3,0),new Point(4,0),new Point(4,1),new Point(4,2)};
                boxLine.setColor(Color.GREEN);
                break;


        }

    }

    //监听Home键
    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        //点击Home键就让游戏暂停
        ispasue=true;
        //发送通知
        notifyIntent=new Intent(this, NotificationService.class);
        startService(notifyIntent);
        if(musicIntent!=null) {
            stopService(musicIntent);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(notifyIntent!=null){
            stopService(notifyIntent);
        }
        if(musicIntent!=null) {
            stopService(musicIntent);
        }

    }

    @Override
    protected void onResume() {
       // Toast.makeText(GameActivity.this,"resume",Toast.LENGTH_SHORT).show();
        Log.d("1","回到应用");

        //活动一启动就会调用onCreate(),onResume()方法,点击Home键就会调用onpause(),再次回到应用就会调用onResume()方法

            startService(musicIntent);

        super.onResume();
    }
}
